using System;
using System.Runtime.InteropServices;
using System.IO;

namespace KodeIT.Web.Hosting
{
    [ClassInterface(ClassInterfaceType.None)]
    public sealed class ProxySetup : IProxySetup
    {
        private AppDomain _domain;

        #region IProxySetup Members

        _AppDomain IProxySetup.LoadDomain(string nativeFilename)
        {
            if (null == _domain)
            {
                try
                {
                    AppDomainSetup setup = new AppDomainSetup();
                    string domainDirectory = Path.Combine(Path.GetDirectoryName(nativeFilename), "bin");
                    setup.ApplicationName = "httpFilters";
                    setup.ApplicationBase = domainDirectory;
                    setup.ConfigurationFile = "filter.config";
                    setup.PrivateBinPath = domainDirectory;
                    setup.ShadowCopyFiles = "true";
                    _domain = AppDomain.CreateDomain("httpFilters", null, setup);
                }
                catch (Exception exp)
                {
                    EventHelper.Write("Unable to create AppDomain", exp);
                    throw;
                }
            }

            return _domain as _AppDomain;
        }

        void IProxySetup.UnloadDomain()
        {
            if (null != _domain)
            {
                try
                {
                    AppDomain.Unload(_domain);
                }
                catch (Exception exp)
                {
                    EventHelper.Write("Unable to unload AppDomain", exp);
                }
            }
        }

        #endregion
    }
}
